<?php

namespace app\admin\controller\sku;

use app\common\controller\AdminBase;
use think\App;
use think\facade\Db;
use util\Excel;

/**
 * Count控制器
 */
class Count extends AdminBase
{

    protected $model = null;

    protected $validate = null;

    protected $relationSearch = false;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\SkuCount();

        $this->validate = \app\admin\validate\SkuCount::class;
    }


    /**
     * 列表
     */
    public function index()
    {
        //默认bra01 is_output 默认不导出
        $filters = $this->request->get('filter', '{}');
        $filters = json_decode($filters, true);
        $brand_id = !empty($filters['brand_name']) ? $filters['brand_name'] : '1';
        $brand = table('brand')->where(['id' => $brand_id])->find();
        //品牌大写转小写
        $brand_name = strtolower($brand['title']);
        $start_time = !empty($filters['time'][0]) ? strtotime($filters['time'][0]) : mktime(0, 0, 0, date('m'), 1, date('Y'));
        $end_time =  !empty($filters['time'][1]) ? strtotime($filters['time'][1]) : time();
        $is_output = !empty($this->request->get('is_output')) ? $this->request->get('is_output') : 0;
        $sql = "SELECT 
        c.sku,
        sum(b.quantity) as count,
        b.title,
        e.handle_url,
        b.product_id,
        c.variants_id as SKUid
        FROM qu_order as a
        LEFT JOIN qu_order_quantity as b ON a.id=b.order_id
        LEFT JOIN qu_order_sku as c ON b.variant_id=c.variants_id
        LEFT JOIN qu_order_product as e ON b.product_id=e.product_id
        where a.financial_status = 'paid'
        AND a.created_at >= " . $start_time . "
        AND a.created_at <= " . $end_time . "
        AND c.id > 1
        AND b.sku like '%{$brand_name}%'
        GROUP BY SKUid
        ORDER BY count DESC
    ";
        $join_datas = Db::query($sql);
        // halt($join_datas);
        if (!$join_datas) {
            return [];
        }
        foreach ($join_datas as $k => $v) {
            $explode_arr = explode('-', strtolower($v['sku']));
            if (isset($explode_arr[1])) {
                $color[$k] = explode('+', $explode_arr[1]);
            }
        }
        foreach ($join_datas as $k => $v) {
            $explode_arr = explode('-', strtolower($v['sku']));
            if (isset($explode_arr[2])) {
                $size[$k] = $explode_arr[2];
            }
        }
        $color = $this->array_unique_fb($color);
        $size = array_unique($size);
        // sort($size);
        $size = array_values($size);
        foreach ($size as $v) {
            $sort_size[$v] = $this->size_sort($v);
        }
        $sort_size = array_flip($sort_size);
        ksort($sort_size);
        $sort_size = array_values($sort_size);
        asort($color);
        $merge_sku[$brand_name] = 0;
        foreach ($color as   $v) {
            $merge_sku[$brand_name . '_' . $v] = 0;
            foreach ($sort_size as $vl) {
                $merge_sku[$brand_name . '_' . $v . '_' . $vl] = 0;
            }
        }
        // halt($color, $size, $merge_sku);

        //bra01-black+blue-xl-2
        foreach ($join_datas as $join_data) {
            //数量
            $multiple = 1;
            $sku_title_arr =  explode('-', strtolower($join_data['sku']));
            file_put_contents('sku.txt', $join_data['sku']);
            if (isset($sku_title_arr[0])) {
                if (isset($sku_title_arr[1])) {
                    if (isset($sku_title_arr[3])) {
                        $multiple = $sku_title_arr[3];
                    }
                    $sku_title_arr1 =  explode('+', $sku_title_arr[1]);
                    foreach ($sku_title_arr1 as $vl) {
                        $merge_sku[$sku_title_arr[0]] = $merge_sku[$sku_title_arr[0]] + ((int)$join_data['count']) * $multiple;
                        $merge_sku[$sku_title_arr[0] . '_' . $vl] = $merge_sku[$sku_title_arr[0] . '_' . $vl] + ((int)$join_data['count']) * $multiple;
                        if (isset($sku_title_arr[2])) {
                            $merge_sku[$sku_title_arr[0] . '_' . $vl . '_' . $sku_title_arr[2]] = $merge_sku[$sku_title_arr[0] . '_' . $vl . '_' . $sku_title_arr[2]]  + ((int)$join_data['count']) * $multiple;
                        }
                    }
                }
            }
        }

        foreach ($merge_sku as $k => $v) {
            if ($v == 0) {
                unset($merge_sku[$k]);
            }
        }
        $merge_sku_new = array();
        foreach ($merge_sku as $k => $v) {
            $merge_sku_new[] =
                ['sku' => $k, 'count' => $v];
        }

        if ($is_output == 1) {
            $header = [['sku', 'sku'], ['count', 'count']];
            return Excel::exportData($merge_sku_new, $header, $brand_name, 'xlsx');
        }
        $data = [
            'code' => 1,
            'msg' => '',
            'count' => count($merge_sku_new),
            'data' => $merge_sku_new,
        ];
        return json($data);
    }

    /**
     * 去掉重复的值
     */
    public function array_unique_fb($array2D)
    {
        foreach ($array2D as $k => $v) {
            $v = join(',', $v); //降维,也可以用implode,将一维数组转换为用逗号连接的字符串
            $temp[$k] = $v;
        }
        $temp = array_unique($temp); //去掉重复的字符串,也就是重复的一维数组
        $temp = implode(',', $temp);
        $temp = explode(',', $temp);
        return  array_unique($temp);
    }
    //通过时间查找编号的出单数
    public function count_brandlist()
    {
        $post = $this->request->post();
        $start_time = !empty($post['start_time']) ? $post['start_time'] : strtotime(date('Y-m-d 00:00:00', time() - 15 * 3600));
        $start_time = strtotime(date('Y-m-d 00:00:00', $start_time));
        if ($post['day_changes'] == 3) {
            $start_time = strtotime(date('Y-m-1 00:00:00', $start_time));
        }
        $end_time = !empty($post['end_time']) ? $post['end_time'] : strtotime(date('Y-m-d 00:00:00', time() + 9 * 3600));
        if ($post['day_changes'] == 101) {
            $end_time = strtotime(date('Y-m-d 23:59:59', $end_time));
        } else {
            $end_time = strtotime(date('Y-m-d 00:00:00', $end_time));
        }
        $start_time = date('Y-m-d', $start_time);
        $end_time = date('Y-m-d', $end_time);
        $where[] = ['counttime', '>=', $start_time];
        $where[] = ['counttime', '<=', $end_time];
        $results  = table('brandcount')->field('SUM(count) AS sum, brand')->where($where)->group('brand')->order('sum desc')->select()->toarray();
        $data = [
            'code' => 1,
            'msg' => '',
            'data' => $results,
        ];
        return json($data);
    }

    /**
     * 尺码排序
     */
    public function size_sort($size)
    {
        // ['s', 'm', 'l', 'xl', '2xl', '3xl', '4xl', '5xl', '6xl', '7xl']
        switch ($size) {
            case 's':
                return  1;
                break;
            case 'm':
                return  2;
                break;
            case 'l':
                return 3;
                break;
            case 'xl':
                return 4;
                break;
            case '2xl':
                return 5;
                break;
            case '3xl':
                return 6;
                break;
            case '4xl':
                return 7;
                break;
            case '5xl':
                return 8;
                break;
            case '6xl':
                return 9;
                break;
            case '7xl':
                return 10;
                break;
            default:
                return $size;
                break;
        }
    }
}
